<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\Admin\PaperImportRequest;
use App\Models\Course;
use App\Models\Knowledge;
use App\Models\LitQuestion;
use App\Models\PaperReal;
use App\Models\PaperUploads;
use App\Models\Questions;
use App\Service\Office\GetDocx;
use App\Service\Office\PaperImportService;
use App\Service\Office\WordService;
use Carbon\Carbon;
use DB;
use Exception;
use Illuminate\Http\JsonResponse;
use Log;

class PaperController extends AdminBaseController
{

    public function index() {
        $wh = [];
        if ($this->user->role != 'admin') {
            $wh['tiku_paper_uploads.uid'] = $this->user->id;
        }

        $list = PaperUploads::filter(request()->all())
            ->selectRaw('tiku_paper_uploads.*, tiku_course.courseName, tiku_course.studyName, tiku_course.fullName as courseFullName')
            ->join('tiku_course', 'tiku_paper_uploads.courseId', '=', 'tiku_course.id')
            ->orderByDesc('tiku_paper_uploads.id')
            ->where($wh)
            ->paginate(request('perPage', 10));

        foreach ($list->items() as $item) {
            $ids = array_reduce($item->ids, function($carry, $item) {
                return array_merge($carry, $item);
            }, []);
            $pCount = 0;
            $cCount = 0;
            foreach ($ids as $id) {
                $_cCount = LitQuestion::where('parentId', $id)->count();
                if ($_cCount > 0) $cCount+=$_cCount;
                else $pCount+=1;
            }
            $item->pCount = $pCount;
            $item->cCount = $cCount;
            $item->qCount = $pCount + $cCount;
        }

        return $this->restful($list);
    }

    /**
     * 详情
     * @param $id
     * @return JsonResponse|object
     */
    public function show($id) {
        $paper = PaperUploads::findOrFail($id);
        $idsInPaper = array_values($paper->ids);
        $questionIds = [];
        foreach ($idsInPaper as $v) {
            $questionIds = array_merge($questionIds, $v);
        }
        $paper->questions = DB::table('tiku_questions')->whereIn('id', $questionIds)->get();
        foreach ($paper->questions as &$question) {
            $question->optionHtmlList = replaceStaticFileUrlInString($question->optionHtmlList);
            $question->answer = replaceStaticFileUrlInString($question->answer);
            $question->answerHtml = replaceStaticFileUrlInString($question->answerHtml);
            $question->anylysis = replaceStaticFileUrlInString($question->anylysis);
            $question->anylysisHtml = replaceStaticFileUrlInString($question->anylysisHtml);
            $question->bodyhtml = replaceStaticFileUrlInString($question->bodyhtml);
            $question->children = LitQuestion::where('parentId', $question->id)->get();
        }

        return $this->restful($paper);
    }

    /**
     * 删除
     * @param int $id
     * @return JsonResponse|object
     */
    public function destroy(int $id)
    {
        $paper = PaperUploads::findOrFail($id);

        DB::transaction(function () use ($paper) {
            $wh = [];
            if ($this->user->role != 'admin') {
                $wh['uid'] = $this->user->id;
            }

            // 删除所有试题
            $questionIds = [];
            $idsInPaper = array_values($paper->ids);
            foreach ($idsInPaper as $v) {
                $questionIds = array_merge($questionIds, $v);
            }
            $questionResult = DB::table('tiku_questions')->where($wh)->whereIn('id', $questionIds)->delete();
            if ($questionResult > 0) {
                // 删除小题
                LitQuestion::whereIn('parentId', $questionIds)->where($wh)->delete();
            }

            // 删除试卷
            $paper->delete();
        });

        return $this->restful();
    }

    /**
     * 审核通过
     * @return JsonResponse|object
     * @throws Exception
     */
    public function pass() {
        $id = request('id');
        if (!$id) {
            throw new Exception('试卷不存在');
        }

        DB::transaction(function () use ($id) {
            $paper = PaperUploads::findOrFail($id);
            $paper->status = 1;
            $paper->save();

            $paper = $paper->toArray();
            $paper['ids'] = json_encode($paper['ids']);
            PaperReal::insertGetId($paper);
        });

        return $this->restful();
    }

    /**
     * 试卷导入
     * @param PaperImportRequest $request
     * @param WordService $wordService
     * @param PaperImportService $paperImport
     * @return JsonResponse|object
     * @throws \PhpOffice\PhpWord\Exception\Exception
     * @throws Exception
     */
    public function import(PaperImportRequest $request, WordService $wordService, PaperImportService $paperImport) {
        // 表单数据
        $params = $request->validated();
        if (empty($params['pathType'])) $params['pathType'] = 1;
        if ($params['pathType'] == 2) {
            $filePath = $params['filePath'];
        } else {
            $filePath = storage_path($params['filePath']);
        }

        if (empty($params['city'])) $params['city'] = null;

        $wordService->imgPath = 'tikuimg/paper/'.$params['courseId'].'/'.Carbon::now()->format('Y/m').'/';
        $paperImport->imgPath = 'tikuimg/paper/'.$params['courseId'].'/'.Carbon::now()->format('Y/m').'/';

        // 所有题目，目前只记录父级题目
        $questionIds = [];
        // 根据题型对题目id分组
        $questionTypeIds = [];

        try {
            // docx 转 html
            $html = $wordService->docx2html($filePath);

            // 解析试卷
            $questions = $wordService->htmlHandle($html, $params['courseId']);
        }catch (Exception $e) {
            Log::error('[试卷导入-格式有误-异常]', (array)$e);
            if (mb_strpos($e->getMessage(), 'Invalid image') !== false) throw new Exception('试卷格式有误（文档图片格式不支持）');
            throw new Exception('试卷格式有误（'.$e->getMessage().'）');
        }

        // 入库
        try {
            // 试题入库
            foreach ($questions as $question) {
                $Q = $paperImport->saveQuestionToDatabase($question, $params['courseId'], $params['province'], $params['city'], true);
                if ($Q) {
                    $questionIds[] = $Q['id'];
                    $questionTypeIds[$Q['questionTypeId']][] = $Q['id'];
                }else {
                    throw new Exception('试题入库失败');
                }
            }

            ksort($questionTypeIds);
            // 试卷入库
            $paperSaveResult = DB::table('tiku_paper_uploads')->insert([
                'courseId' => $params['courseId'],
                'year' => $params['year'],
                'title' => $params['title'],
                'province' => $params['province'],
                'cityName' => $params['city'],
                'ids' => json_encode($questionTypeIds),
                'uid' => isset($this->user) ? $this->user->id : 0, // 上传者
                'paperType' => $params['paperType'],
                'questionCount' => count($questionIds),   // 题目数量
                'createtime' => Carbon::now(),   // 入库时间
                'url' => $filePath,   // 试卷保存路径
                'status' => 0,   // 状态
            ]);

            if (!$paperSaveResult) {
                throw new Exception('试卷入库失败');
            }

        }catch (Exception $e) {
            Log::error('[试卷导入]', (array)$e);
            Log::error($e->getMessage());
            throw new Exception('导入失败');
        }

        // 成功
        return $this->restful($questionTypeIds);
    }
}
